import Vue from 'vue';
import VueI18n from 'vue-i18n';
import { messages } from '@common/components/common/i18n';
import {cloneDeep} from 'lodash';
import Dialog from './dialog';
import utils from "@common/utils/utils";
import { ElDialog, genProps } from "@common/components/custom/attributes";

const i18n = new VueI18n({
	locale: 'zh-CN',
	messages
});

const getActiveTabDialogContainer = () => {
	let tabsWrapper = $('#app').find('.tabs_wrapper');
	if (tabsWrapper.length > 0) {
		let activeTabs = $(tabsWrapper).find('.el-tabs__nav').find('.el-tabs__item.is-active');
		let tabPane = $(activeTabs).attr('aria-controls');
		let tabContainer = $(tabsWrapper).find(`#${tabPane}`);
		return $(tabContainer).find('.tab_content').find(`#dialog-${tabPane.replace('pane-', '')}`);
	}
	return $('#app').find('.app_content').find('#dialog-container');
};

const closeBtn = options => {
    const componentOption = options.component;
    return {
        text: '关闭',
        click (dialog) {
            typeof componentOption.event === 'function' && componentOption.event({ type: 'closeEvent'}, dialog);
            dialog.visible = false;
        },
    };
};

const confirmBtn = {
	type: 'primary',
	text: '确定',
	loading: true,
	click (dialog, $refs) {
		dialog.visible = false;
	},
};

const procFooterButtons = options => {
	let buttons = options.buttons || [];
	if (utils.isNotEmptyList(buttons)) {
		return buttons;
	}
	let close = $.extend({}, closeBtn(options), (options.closeBtn || {}));
	if (!options.noCloseBtn) {
		buttons.push(close);
	}
	if (options.hideConfirmBtn) {
		return buttons;
	}
	const componentOption = options.component;
	if (componentOption) {
		let componentRef = componentOption.ref || 'component';
		let confirm = $.extend({}, confirmBtn, {
			click (dialog, $refs) {
				let component = $refs[componentRef];
				if (component && typeof component.confirm === 'function') {
					component.confirm().then(valid => {
						if (valid) {
							typeof options.confirmed === 'function' && options.confirmed(component);
							dialog.visible = false;
						}
					});
				}
			},
		}, (options.confirmBtn || {}));
		buttons.push(confirm);
	} else if (options.confirmBtn) {
		let confirm = $.extend({}, confirmBtn, options.confirmBtn);
		buttons.push(confirm);
	}
	return buttons;
};

const DialogConstructor = Vue.extend(Dialog);
const GlobalDialog = (store, router) => {
	return options => {
		const propsData = {};
		let dialogPropKeys = Object.keys(ElDialog);
		for (let field in options) {
			if (dialogPropKeys.indexOf(field.replace('Fn', '')) === -1) {
				propsData[field] = options[field];
			}
		}
		propsData.dialogProps = genProps(ElDialog, options);
		Object.assign(propsData, {
			data: cloneDeep(options.data),
			closed () {
				const closed = options.closed;
				if (closed) {
					closed();
				}
				if (options.appendToBody) {
					document.body.removeChild(instance.$el);
				} else {
					$(instance.$el).remove();
				}
			},
		});
		const componentOption = options.component;
		if (componentOption) {
			propsData.component = componentOption.value;
			propsData.componentRef = componentOption.ref;
			propsData.componentProps = componentOption.props;
			propsData.componentEvent = componentOption.event;
			if (!(componentOption.value instanceof Object)) {
				delete propsData.component;
			}
		}
		propsData.buttons = procFooterButtons(options);
		const instance = new DialogConstructor({
			inheritAttrs: true,
			store,
			router,
			i18n,
			propsData,
		});
		instance.$mount();
		if (options.appendToBody) {
			document.body.appendChild(instance.$el);
		} else {
			$(getActiveTabDialogContainer()).append(instance.$el);
		}
		Vue.nextTick(() => {
			instance.visible = true;
		});
		return instance;
	};
};

export default GlobalDialog;
